<template>
    <div class="app-container">
        <el-button @click="backClick" type="primary" size="small">返回列表</el-button>
        <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="110px" style="margin: 20px 50px 0px;">
            <el-tabs type="border-card" v-model="activeName">
                <el-tab-pane label="基本信息" name="1">
                    <el-form-item label="产品名称：" prop="name">
                        <el-input v-model="dataForm.name" placeholder="必填项。请输入产品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="产品编码：" prop="code">
                        <el-input v-model="dataForm.code" placeholder="必填项。请输入产品编码"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="是否组合产品：" prop="combined">
                        <el-radio-group v-model="dataForm.combined" @change="combinedChange">
                            <el-radio label="0">是</el-radio>
                            <el-radio label="1">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="产品套餐：" v-if="dataForm.combined == 0">
                        <el-tag v-for="(item,index) in productUnitArr" :key="index" closable effect="plain" type="primary" size="small" @close="handleClose(item,index)" style="margin-right:5px;">{{item}}</el-tag>
                        <el-button @click="openAddProduct" size="mini" type="primary" icon="el-icon-circle-plus-outline">添加产品</el-button>
                    </el-form-item> -->
                    <!-- 产品分类 -->
                    <el-form-item label="产品分类：" prop="productCategoryIdList">
                        <el-cascader clearable :options="categoryList" :props="{ checkStrictly: true, value: 'id', label: 'name' }"  v-model="categoryId" change-on-select placeholder="请选择产品分类" style="width: 100%;"></el-cascader>
                    </el-form-item>
                    <el-form-item label="产品主图：" prop="coverImage">
                        <el-upload class="avatar-uploader" action="" :http-request="UploadImage" :show-file-list="false" :before-upload="beforeAvatarUpload" >
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" width="100%">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="产品背景图：" prop="backgroundImage">
                        <el-upload class="avatar-uploader" action="" :http-request="UploadbackgroundImage" :show-file-list="false" :before-upload="beforeAvatarUpload" >
                            <img v-if="backgroundImageUrl" :src="backgroundImageUrl" class="avatar" width="100%">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="优惠规则：" prop="keyword">
                        <el-table
                            ref="multipleTables"
                            :data="ruleData"
                            tooltip-effect="dark"
                            style="width: 100%" border
                            @select="selectChange" @select-all="selectAllChange">
                            <el-table-column type="selection" width="55" align="center"></el-table-column>
                            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                            <el-table-column prop="rulesScore" label="金额" align="center"></el-table-column>
                            <el-table-column prop="rulesRatio" label="可得积分数" align="center"></el-table-column>
                            <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
                        </el-table>
                    </el-form-item>
                    <el-form-item label="产品摘要：" prop="summary">
                        <el-input v-model="dataForm.summary" type="textarea" :rows="4" placeholder="请输入产品摘要"></el-input>
                    </el-form-item>
                    <el-form-item label="关键字：" prop="keyword">
                        <el-input v-model="dataForm.keyword" placeholder="请输入关键字"></el-input>
                    </el-form-item>
                    <el-form-item label="计数单位：" prop="countingUnit">
                        <el-input v-model="dataForm.countingUnit" placeholder="请输入计数单位"></el-input>
                    </el-form-item>
                    <el-form-item label="是否免运费：" prop="freeFreighted">
                        <el-radio v-model="dataForm.freeFreighted" label="0">是</el-radio>
                        <el-radio v-model="dataForm.freeFreighted" label="1">否</el-radio>
                    </el-form-item>
                    <el-form-item label="浏览量：" prop="pv">
                        <el-input v-model="dataForm.pv" type="number" placeholder="请输入浏览量"></el-input>
                    </el-form-item>
                    <el-form-item label="顺序值：" prop="sort">
                        <el-input v-model="dataForm.sort" type="number" placeholder="请输入顺序值"></el-input>
                    </el-form-item>
                    <el-form-item label="可购买状态：" prop="purchasable">
                        <el-radio v-model="dataForm.purchasable" label="1">可购买</el-radio>
                        <el-radio v-model="dataForm.purchasable" label="0">不可购买</el-radio>
                    </el-form-item>
                    <el-form-item label="上下架：" prop="upDownStatus">
                        <el-radio v-model="dataForm.upDownStatus" label="1">上架</el-radio>
                        <el-radio v-model="dataForm.upDownStatus" label="0">下架</el-radio>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="产品模型" name="2">
                    <!-- 产品spu -->
                    <el-form-item label="产品模型：" prop="productSpuId">
                        <el-select v-model="dataForm.productSpuId" placeholder="请选择" @change="productSpuChange" style="width: 100%;">
                            <el-option v-for="item in propList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="扩展属性：" prop="productSpuList">
                        <div v-for="(item,index) in productPropEntityVoList" :key="index">
                            <span style="padding-right: 5px;color: #606266;width: 80px;display: inline-block;">{{item.propName}}：</span>
                            <el-checkbox-group v-model="productPropEntityVo[index]" @change="productPropEntityVoChange(productPropEntityVo[index],item.productPropValueEntityList, item.id, item.propName, index)" style="display: inline-block;">
                                <el-checkbox :label="val.id" v-for="(val,ind) in item.productPropValueEntityList" :key="ind">{{val.propValue}}</el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                    <el-form-item label="模型描述：" prop="spuDescription">
                        <quill-editor v-model="spuDescription" ref="mySpuQuillEditor" style="margin-bottom: 58px;" :options="editorOption" placeholder="请输入">
                        </quill-editor>
                        <!-- 文件上传input 将它隐藏-->
                        <el-upload action="" :http-request="qnSpuUpload" ref="spuupload" style="display:none">
                            <el-button size="small" type="primary" id="imgSpuInput">点击上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="产品规格" name="3">
                    <!-- 产品sku -->
                    <el-form-item label="产品规格：" prop="productSkuList">
                        <el-row>
                            <el-col :span="12" style="padding: 0px 10px 0px 0px;">
                                <el-select v-model="productSkuId" placeholder="请选择规格" @change="productSkuChange" style="width: 100%;">
                                    <el-option v-for="item in specList" :key="item.id" :label="item.specName" :value="item.id"></el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="12" style="padding: 0px 0px 0px 10px;">
                                <el-select v-model="productSkuValue" placeholder="请选择规格值" @change="productSkuChoose" style="width: 100%;">
                                    <el-option v-for="item in productSpecValueEntityList" :key="item.id" :label="item.tooltip" :value="item.id"></el-option>
                                </el-select>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <el-form-item label="基本数据：" style="color: #606266;text-align: center;">
                        <el-table :data="tabAllSkuArr" border ref="multipleTable" tooltip-effect="dark" style="width: 100%">
                            <el-table-column label="产品货号" align="center">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.productCode"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column v-for='(col,index) in tabSku' :label="col.title" :key="index" width="124px" align="center">
                                <template slot-scope="scope">
                                    {{scope.row[col.title]}}
                                </template>
                            </el-table-column>
                            <el-table-column label="库存" align="center">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.quantity" type="number"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="价格" align="center">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.retailPrice" type="number"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="批发价" align="center">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.tradePrice" type="number"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="重量" align="center">
                                <template slot-scope="scope">
                                    <el-input v-model="scope.row.weight" type="number"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80" align="center" fixed="right">
                                <template slot-scope="scope">
                                    <el-button size="mini" plain type="danger" @click="delTabColOne(scope.$index)" >删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="产品描述" name="4">
                    <quill-editor v-model="description" ref="myQuillEditor" style="margin-bottom: 58px;" :options="editorOption" placeholder="请输入">
                    </quill-editor>
                    <!-- 文件上传input 将它隐藏-->
                    <el-upload action="" :http-request="qnUpload" ref="upload" style="display:none">
                        <el-button size="small" type="primary" id="imgInput">点击上传</el-button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="产品相册" name="5">
                    <el-upload action="" list-type="picture-card" :http-request="UploadImageArr" :file-list="filesList" :on-preview="handlePictureCardPreview" :before-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-tab-pane>
                <el-form-item style="text-align: center;margin:30px 0px 0px -100px;">
                    <el-button v-show="activeName != '1'" @click="prevClick('dataForm')" type="primary">上一步</el-button>
                    <el-button v-show="activeName != '5'" @click="nextClick('dataForm')" type="primary">下一步</el-button>
                    <el-button v-show="activeName == '5'" @click="saveClick('dataForm')" type="primary">提交</el-button>
                </el-form-item>
            </el-tabs>
        </el-form>
        <!-- 弹框 -->
        <el-dialog :visible.sync="showDialog" width="800px">
            <el-form ref="addProductForm" :rules="addProductRules" :model="addProductForm" label-position="left" label-width="120px" style="margin: 0px 50px;">
                <el-form-item label="产品套餐：">
                    <el-tag v-for="(item,index) in productUnitArr" :key="index" closable size="small" @close="handleClose(item,index)" style="margin-right:5px;">{{item}}</el-tag>
                </el-form-item>
                <el-form-item label="产品：" prop="unitProductId">
                    <el-select v-model="addProductForm.unitProductId" placeholder="请选择" style="width: 100%;">
                        <el-option v-for="(item,index) in productListOpt" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量：" prop="quantity">
                    <el-input v-model="addProductForm.quantity" type="number"></el-input>
                </el-form-item>
                <el-form-item label="顺序值：" prop="sort">
                    <el-input v-model="addProductForm.sort" type="number"></el-input>
                </el-form-item>
                <el-form-item style="text-align: center;margin:30px 0px 0px -100px;">
                    <el-button @click="addProductClick('addProductForm')" type="primary">添加产品</el-button>
                    <el-button @click="cancelProductClick('addProductForm')">关闭</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import {quillEditor, Quill} from 'vue-quill-editor'
import {container, ImageExtend} from 'quill-image-extend-module'
Quill.register('modules/ImageExtend', ImageExtend)
import { addProduct, findProduct, sortProduct, upDownProduct, editProduct, detailProduct, delProduct } from '@/api/product/product'
import { findPreferential } from '@/api/product/preferential-rules'
import { findCategory } from '@/api/product/product-category'
import { findProp, detailProp } from '@/api/product/product-property'
import { findSpec, detailSpec } from '@/api/product/product-specification'
import { uploadPic, getPic } from '@/api/uploadPic'
import { constants } from 'crypto';
export default {
    name: 'ProductEdit',
    data() {
        return{
            tableData: [],
            ruleData: [],
            nowId: '',
            showDialog: false,
            dataForm: {
                backgroundImage: '',
                code: '',
                combined: '1',
                countingUnit: '',
                coverImage: '',
                description : '',
                freeFreighted: '0',
                keyword: '',
                name: '',
                productAlbumEntityList: [],
                productCategoryIdList: [],
                productSkuList: [],
                productSpuId: '',
                productSpuList: [],
                spuDescription: '',
                productUnitEntityList: [],
                purchasable: '1',
                pv: '',
                sort: '',
                summary: '',
                upDownStatus: '1',
                preferentialRulesId: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入产品名称', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入产品编码', trigger: 'blur' }
                ],
            },
            description: '',
            spuDescription: '',
            productSpuList: [],
            addProductForm: {
                unitProductId: '',
                quantity: '',
                sort: ''
            },
            addProductRules: {
                unitProductId: [
                    { required: true, message: '请选择产品', trigger: 'change' }
                ],
                quantity: [
                    { required: true, message: '请输入数量', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '请输入顺序值', trigger: 'blur' }
                ],
            },
            nowPage: 1,
            pageSize: 10,
            imageUrl: '',
            backgroundImageUrl: '',
            popStatus: 0,  //0为添加，1为修改
            pageData: {},
            showPicDialog: false,
            nowPic: '',
            productCategoryOpt: [],
            activeName: '1',
            parentOpt: [],
            categoryOpt: [],
            parentId: '',
            propertyData: [],
            editorOption: {
                // placeholder设置提示词
                placeholder: '请输入正文......',
                // modules设置工具栏
                modules: {
                    toolbar: [
                        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
                        ["blockquote", "code-block"], // 引用  代码块
                        [{ header: 1 }, { header: 2 }], // 1、2 级标题
                        [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
                        [{ script: "sub" }, { script: "super" }], // 上标/下标
                        [{ indent: "-1" }, { indent: "+1" }], // 缩进
                        [{'direction': 'rtl'}],                         // 文本方向
                        [{ size: ["small", false, "large", "huge"] }], // 字体大小
                        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
                        [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
                        [{ font: [] }], // 字体种类
                        [{ align: [] }], // 对齐方式
                        ["clean"], // 清除文本格式
                        ["link", "image", "video"] // 链接、图片、视频
                    ]
                }
            },
            dialogImageUrl: '',
            dialogVisible: false,
            filesList: [],
            categoryList: [],
            categoryId: [], //产品分类id
            specList: [],
            propList: [],
            productSpecValueEntityList: [],  //规格值列表
            productSkuValue: '',  //规格值
            productPropEntityVoList: [],  //属性  列表
            productPropEntityVo: [],
            tabSku: [],
            tabSkuShowArr: [],
            tabAllSkuArr: [],
            tabSkuSubmitArr: [],
            productListOpt: [],
            productUnitArr: [],
            spuType: 1,
            serialTableArray: [],
            productSkuId: '',
            uploadData: [],
            uploadSpuData: [],
        }
    },
    methods: {
        //默认函数
        init(){
            let _this = this;
            _this.popStatus = this.$route.query.type;
            if(this.$route.query.id){  //编辑
                this.nowId = this.$route.query.id;
                this.detailFun(this.nowId);
            }else{
                this.productList();
            }
        },
        //优惠规则列表
        preferentialList(){
            const _this = this;
            findPreferential(0, 10000, 1, '', '').then(response => {
                if(response.code == 200){
                    _this.ruleData = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //产品列表
        productList(){
            const _this = this;
            //获取列表信息
            findProduct(0, 10000, 1, '', 1).then(response => {
                if(response.code == 200){
                    _this.productListOpt = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取产品分类
        getCategoryList(){
            const _this = this;
            findCategory(0, 10000, '', '').then(response => {
                if(response.code == 200){
                    _this.categoryList = _this.getTreeData(response.object.content);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取产品规格sku
        getProductSku(){
            const _this = this;
            findSpec(0, 10000).then(response => {
                if(response.code == 200){
                    _this.specList = _this.getTreeData(response.object.content);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //获取产品模型spu
        getProductSpu(){
            const _this = this;
            findProp(0, 10000).then(response => {
                if(response.code == 200){
                    _this.propList = _this.getTreeData(response.object.content);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            for(var i=0;i<data.length;i++){
                if((data[i].children == null) || (data[i].children.length<1)){
                    data[i].children=undefined;
                }else {
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },
        toggleSelection(rows) {
            if (rows) {
            rows.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row);
            });
            } else {
            this.$refs.multipleTable.clearSelection();
            }
        },
        selectChange(val){
            if(val.length == 1){
                this.dataForm.preferentialRulesId = val[0].id
            }else if(val.length > 1){
                this.$refs.multipleTables.clearSelection()
                this.$refs.multipleTables.toggleRowSelection(val[1])
                this.dataForm.preferentialRulesId = val[1].id
            }
        },
        selectAllChange(val){
            this.$refs.multipleTables.clearSelection()
        },
        //返回列表
        backClick(){
            this.$router.push({path:'/product/product/list'})
        },
        //上一步
        prevClick(){
            if(parseInt(this.activeName) != 1){
                this.activeName = (parseInt(this.activeName) - 1).toString();
            }
        },
        //下一步
        nextClick(){
            if(parseInt(this.activeName) != 5){
                this.activeName = (parseInt(this.activeName) + 1).toString();
            }
        },
        //移除相册
        handleRemove(file, fileList) {
            let sub = this.getArrIndex(fileList,file);
            this.dataForm.productAlbumEntityList.splice(sub,1);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        // 全路径  编辑器内容
        gerQuill(obj,type){
            const _this = this;
            //type   1为产品描述   2为spu描述
            let descriptionStr = obj;
            //产品描述  编辑器  图片
            descriptionStr.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                //获取全路径
                getPic(capture).then(res => {
                    if(res.code == 200){
                        let sub = descriptionStr.indexOf('<img src="'+ capture +'">');
                        descriptionStr = descriptionStr.replace('<img src="'+ capture +'">','');
                        descriptionStr = descriptionStr.slice(0,sub) + '<img src="'+ res.object +'">' + descriptionStr.slice(sub,descriptionStr.length);
                        if(type == 1){
                            _this.uploadData.push({saveImage: capture,showImage: res.object,type: 'image'})
                        }else if(type == 2){
                            _this.uploadSpuData.push({saveImage: capture,showImage: res.object,type: 'image'})
                        }
                    }else{
                        _this.$message.error(res.message);
                    }
                })
            });
            //产品描述  编辑器  视频
            descriptionStr.replace(/<iframe [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                //获取全路径
                getPic(capture).then(res => {
                    if(res.code == 200){
                        let sub = descriptionStr.indexOf('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ capture +'"></iframe>');
                        descriptionStr = descriptionStr.replace('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ capture +'"></iframe>','');
                        descriptionStr = descriptionStr.slice(0,sub) + '<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ res.object +'"></iframe>' + descriptionStr.slice(sub,descriptionStr.length);
                        if(type == 1){
                            _this.uploadData.push({saveImage: capture,showImage: res.object,type: 'video'})
                        }else if(type == 2){
                            _this.uploadSpuData.push({saveImage: capture,showImage: res.object,type: 'video'})
                        }
                    }else{
                        _this.$message.error(res.message);
                    }
                })
            });
            //在处理资源路径之后触发
            setTimeout(function(){
                if(type == 1){
                    _this.description = descriptionStr
                }else if(type == 2){
                    _this.spuDescription = descriptionStr
                }
                
            },1000);
        },
        //获取详情
        detailFun(id){
            const _this= this;
            //获取产品
            findProduct(0, 10000, 1, '', 1).then(response => {
                if(response.code == 200){
                    _this.productListOpt = response.object.content;
                    //获取详情
                    detailProduct(id).then(response => {
                        if(response.code == 200){
                            const obj = response.object;
                            _this.dataForm.backgroundImage = obj.backgroundImage;
                            if(obj.backgroundImage){
                                _this.getPicFun(obj.backgroundImage, 2);
                            }
                            _this.dataForm.code = obj.code;
                            _this.dataForm.combined = obj.combined.toString();
                            _this.dataForm.countingUnit = obj.countingUnit;
                            _this.dataForm.coverImage = obj.coverImage;
                            if(obj.coverImage){
                                _this.getPicFun(obj.coverImage, 1);
                            }
                            _this.dataForm.spuDescription  = obj.spuDescription;
                            let spuDescriptionStr = obj.spuDescription;
                            // 优惠规则
                            _this.dataForm.preferentialRulesId = obj.preferentialRules.id
                            obj.preferentialRulesId = obj.preferentialRules.id
                            _this.ruleData.map((item)=>{
                                if(item.id == obj.preferentialRulesId){
                                    _this.$refs.multipleTables.toggleRowSelection(item)
                                }
                            })

                            _this.dataForm.description  = obj.description;
                            //产品描述   编辑器
                            _this.gerQuill(obj.description,1);
                            //spu描述  编辑器
                            _this.gerQuill(obj.spuDescription,2);
                            _this.dataForm.freeFreighted = obj.freeFreighted.toString();
                            _this.dataForm.keyword = obj.keyword;
                            _this.dataForm.name = obj.name;
                            _this.dataForm.productSpuId = obj.productSpuId;
                            _this.dataForm.purchasable = obj.purchasable.toString();
                            _this.dataForm.pv = obj.pv;
                            _this.dataForm.sort = obj.sort;
                            _this.dataForm.summary = obj.summary;
                            _this.dataForm.upDownStatus = obj.upDownStatus.toString();
                            // 产品套餐  部件
                            _this.productUnitArr = [];
                            if(obj.productUnitEntityList){
                                for(let i=0;i<obj.productUnitEntityList.length;i++){
                                    for(let j=0;j<_this.productListOpt.length;j++){
                                        if(obj.productUnitEntityList[i].unitProductId == _this.productListOpt[j].id){
                                            _this.dataForm.productUnitEntityList.push({
                                                unitProductId: obj.productUnitEntityList[i].unitProductId,
                                                quantity: obj.productUnitEntityList[i].quantity,
                                                sort: obj.productUnitEntityList[i].sort
                                            });
                                            _this.productUnitArr.push(_this.productListOpt[j].name + '【' + obj.productUnitEntityList[i].quantity +'】');
                                        }
                                    }
                                }
                            }
                            // 产品 分类
                            let arr = [];
                            if(obj.productCategoryEntityList){
                                for(let i=0;i<obj.productCategoryEntityList.length;i++){
                                    arr[i] = [obj.productCategoryEntityList[i].id];
                                    if(obj.productCategoryEntityList[i].parentList){
                                        let childArr = [];
                                        for (const key in obj.productCategoryEntityList[i].parentList) {
                                            if (obj.productCategoryEntityList[i].parentList.hasOwnProperty(key)) {
                                                const element = obj.productCategoryEntityList[i].parentList[key];
                                                arr[i].splice(0,0,element.id)
                                            }
                                        }
                                    }
                                }
                            }
                            _this.categoryId = arr;
                            //产品sku
                            let productSkuList = obj.productSkuList;
                            if(productSkuList){
                                findSpec(0, 10000).then(response => {
                                    if(response.code == 200){
                                        _this.specList = _this.getTreeData(response.object.content);
                                        for(let i=0;i<productSkuList.length;i++){  //默认数据
                                            _this.tabAllSkuArr.push({productCode: productSkuList[i].productCode, quantity: productSkuList[i].quantity, retailPrice: productSkuList[i].retailPrice, tradePrice: productSkuList[i].tradePrice, weight: productSkuList[i].weight});
                                            for(let k=0;k<_this.specList.length;k++){  //表头下拉数据
                                                for(let j=0;j<productSkuList[i].productSkuDetailEntityList.length;j++){  //默认数据  值
                                                    if(_this.specList[k].id == productSkuList[i].productSkuDetailEntityList[j].productSpecId){
                                                        _this.tabSku[j] = {'title': _this.specList[k].specName, 'id': _this.specList[k].id};
                                                        _this.tabSkuShowArr[j] = [];
                                                        for(let g=0;g<_this.specList[k].productSpecValueEntityList.length;g++){  //表头下拉数据  值
                                                            if(_this.specList[k].productSpecValueEntityList[g].id == productSkuList[i].productSkuDetailEntityList[j].productSpecValue){
                                                                _this.tabAllSkuArr[i][_this.tabSku[j].title] = _this.specList[k].productSpecValueEntityList[g].specValue;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        for(let i=0;i<productSkuList.length;i++){  //默认数据
                                            for(let k=0;k<_this.specList.length;k++){  //表头下拉数据
                                                for(let j=0;j<productSkuList[i].productSkuDetailEntityList.length;j++){  //默认数据  值
                                                    if(_this.specList[k].id == productSkuList[i].productSkuDetailEntityList[j].productSpecId){
                                                        for(let g=0;g<_this.specList[k].productSpecValueEntityList.length;g++){  //表头下拉数据  值
                                                            if(_this.specList[k].productSpecValueEntityList[g].id == productSkuList[i].productSkuDetailEntityList[j].productSpecValue){
                                                                if(_this.tabSkuShowArr[j].indexOf(_this.specList[k].productSpecValueEntityList[g].specValue) == -1){
                                                                    _this.tabSkuShowArr[j].push(_this.specList[k].productSpecValueEntityList[g].specValue);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }else{
                                        this.$message.error(response.message);
                                    }
                                })
                            }
                            //产品spu
                            _this.productPropEntityVo = [];
                            _this.productSpuList = [];
                            if(obj.productSpuId){
                                detailProp(obj.productSpuId).then(response => {
                                    if(response.code == 200){
                                        _this.productPropEntityVoList = response.object.productPropEntityVoList;
                                        if(obj.productSpuDetailEntityList){
                                            for(let i=0;i<obj.productSpuDetailEntityList.length;i++){  //选中
                                                for(let j=0;j<_this.productPropEntityVoList.length;j++){  //  所有属性
                                                    if(!_this.productPropEntityVo[j]){
                                                        _this.productPropEntityVo[j] = [];
                                                    }
                                                    for(let k=0;k<_this.productPropEntityVoList[j].productPropValueEntityList.length;k++){  //属性值
                                                        if(obj.productSpuDetailEntityList[i].productPropValue == _this.productPropEntityVoList[j].productPropValueEntityList[k].propValue){
                                                            let val = {"id": obj.productSpuDetailEntityList[i].productPropId,"name": obj.productSpuDetailEntityList[i].productPropName, "productPropEntityList": [{"id": _this.productPropEntityVoList[j].productPropValueEntityList[k].id, "propName": _this.productPropEntityVoList[j].productPropValueEntityList[k].propValue}]};
                                                            _this.productSpuList[j] = val;
                                                            _this.productPropEntityVo[j][k] = _this.productPropEntityVoList[j].productPropValueEntityList[k].id;
                                                        }else{
                                                            if(!_this.productPropEntityVo[j][k]){
                                                                _this.productPropEntityVo[j][k] = '';
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }else{
                                            for(let j=0;j<_this.productPropEntityVoList.length;j++){  //  属性
                                                if(!_this.productPropEntityVo[j]){
                                                    _this.productPropEntityVo[j] = [];
                                                    for(let k=0;k<_this.productPropEntityVoList[j].productPropValueEntityList.length;k++){  //属性值
                                                        _this.productPropEntityVo[j][k] = '';
                                                    }
                                                }
                                            }
                                        }
                                    }else{
                                        this.$message.error(response.message);
                                    }
                                })
                            }
                            //产品图片
                            if(obj.productAlbumEntityList){
                                if(obj.productAlbumEntityList.length > 0){
                                    for (const key in obj.productAlbumEntityList) {
                                        if (obj.productAlbumEntityList.hasOwnProperty(key)) {
                                            const element = obj.productAlbumEntityList[key];
                                            _this.dataForm.productAlbumEntityList.push({'photo': element.photo});
                                            getPic(element.photo).then(res => {
                                                if(res.code == 200){
                                                    _this.filesList.push({'url': res.object});
                                                }else{
                                                    _this.$message.error(res.message);
                                                }
                                            })
                                        }
                                    }
                                }
                            }
                        }else{
                            this.$message.error(response.message);
                        }
                    })
                }else{
                    this.$message.error(response.message);
                }
            })
            
        },
        //获取图片
        getPicFun(img, type){
            const _this = this;
            getPic(img).then(res => {
                if(res.code == 200){
                    if(type == 1){  //主图
                        _this.imageUrl = res.object;
                    }else if(type == 2){  //背景图
                        _this.backgroundImageUrl = res.object;
                    }
                }else{
                    _this.$message.error(res.message);
                }
            })
        },
        //提交添加
        saveClick(formName){
            const _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //提交
                    if(!_this.dataForm.preferentialRulesId){
                        this.$message.warning('请选择优惠规则')
                        return
                    }
                    // ---  产品描述start
                    let str = _this.description;
                    //图片
                    _this.description.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                        for(let i=0;i<_this.uploadData.length;i++){
                            let captures = capture.replace(/&amp;/g,'&');
                            if(_this.uploadData[i].showImage == captures){
                                if(_this.uploadData[i].type == 'image'){
                                    let sub = str.indexOf('<img src="'+ capture +'">');
                                    str = str.replace('<img src="'+ capture +'">','');
                                    str = str.slice(0,sub) + '<img src="'+ _this.uploadData[i].saveImage +'">' + str.slice(sub,str.length);
                                }
                            }
                        }
                    });
                    //视频
                    _this.description.replace(/<iframe [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                        for(let i=0;i<_this.uploadData.length;i++){
                            let captures = capture.replace(/&amp;/g,'&');
                            if(_this.uploadData[i].showImage == captures){
                                if(_this.uploadData[i].type == 'video'){
                                    let sub = str.indexOf('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ capture +'"></iframe>');
                                    str = str.replace('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ capture +'"></iframe>','');
                                    str = str.slice(0,sub) + '<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ _this.uploadData[i].saveImage +'"></iframe>' + str.slice(sub,str.length);
                                }
                            }
                        }
                    });
                    _this.dataForm.description = str;
                    //   ---  产品描述end
                    // ---  spu描述start
                    let spuStr = _this.spuDescription;
                    //图片
                    _this.spuDescription.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                        for(let i=0;i<_this.uploadSpuData.length;i++){
                            let captures = capture.replace(/&amp;/g,'&');
                            if(_this.uploadSpuData[i].showImage == captures){
                                if(_this.uploadSpuData[i].type == 'image'){
                                    let sub = spuStr.indexOf('<img src="'+ capture +'">');
                                    spuStr = spuStr.replace('<img src="'+ capture +'">','');
                                    spuStr = spuStr.slice(0,sub) + '<img src="'+ _this.uploadSpuData[i].saveImage +'">' + spuStr.slice(sub,spuStr.length);
                                }
                            }
                        }
                    });
                    //视频
                    _this.spuDescription.replace(/<iframe [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                        for(let i=0;i<_this.uploadSpuData.length;i++){
                            let captures = capture.replace(/&amp;/g,'&');
                            if(_this.uploadSpuData[i].showImage == captures){
                                if(_this.uploadSpuData[i].type == 'video'){
                                    let sub = spuStr.indexOf('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ capture +'"></iframe>');
                                    spuStr = spuStr.replace('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ capture +'"></iframe>','');
                                    spuStr = spuStr.slice(0,sub) + '<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ _this.uploadSpuData[i].saveImage +'"></iframe>' + spuStr.slice(sub,spuStr.length);
                                }
                            }
                        }
                    });
                    _this.dataForm.spuDescription = spuStr;
                    //   ---  spu描述end
                    //产品分类
                    _this.dataForm.productCategoryIdList = [];
                    for(let i=0;i<_this.categoryId.length;i++){
                        _this.dataForm.productCategoryIdList.push(_this.categoryId[i][_this.categoryId[i].length - 1]);
                    }
                    //产品规格  sku
                    _this.dataForm.productSkuList = [];
                    for (const key in _this.tabAllSkuArr) {
                        if (_this.tabAllSkuArr.hasOwnProperty(key)) {
                            const element = _this.tabAllSkuArr[key];
                            _this.dataForm.productSkuList.push({productCode: element['productCode'], quantity: element['quantity'], retailPrice: element['retailPrice'], tradePrice: element['tradePrice'], weight: element['weight'], productSkuDetailEntityList: []});
                            for (const child in element) {    //遍历组装  规格、规格值  id
                                if (element.hasOwnProperty(child)) {
                                    const val = element[child];
                                    if((child != 'productCode') && (child != 'quantity') && (child != 'retailPrice') && (child != 'tradePrice') && (child != 'weight')){
                                        for(let i=0;i<_this.specList.length;i++){   //规格  下拉数据
                                            if(_this.specList[i].specName == child){
                                                for(let j=0;j<_this.specList[i].productSpecValueEntityList.length;j++){  //规格值  下拉数据
                                                    if(_this.specList[i].productSpecValueEntityList[j].specValue == val){
                                                        _this.dataForm.productSkuList[key].productSkuDetailEntityList.push({
                                                            'productSpecId': _this.specList[i].id,
                                                            'productSpecName': _this.specList[i].specName,
                                                            'productSpecValue': _this.specList[i].productSpecValueEntityList[j].id,
                                                            'productSpecValueName': _this.specList[i].productSpecValueEntityList[j].specValue
                                                        });
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //产品模型  spu
                    _this.dataForm.productSpuList = [];
                    for(let i=0;i<_this.productSpuList.length;i++){
                        if(_this.productSpuList[i]){
                            _this.dataForm.productSpuList.push(_this.productSpuList[i]);
                        }
                    }
                    if(_this.popStatus == 0){  //添加
                        addProduct(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                this.$router.push({path:'/product/product/list'});
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        editProduct(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                this.$router.push({path:'/product/product/list'});
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //商品图片上传
        UploadImageArr(param){
            this.UploadImage(param,1);
        },
        //背景图上传
        UploadbackgroundImage(param){
            this.UploadImage(param,2);
        },
        //自定义上传
        UploadImage(param,type){
            const _this = this;
            //上传图片
            let formData = new FormData();
            formData.append('photoFile', param.file);
            formData.append('dir', 'Product');
            formData.append('fileType', '1');
            uploadPic(formData).then(response => {
                if(response.code == 200){
                    if(type){
                        if(type == 1){  //产品图片
                            _this.dataForm.productAlbumEntityList.push({"photo": response.object.saveImage});
                        }else if(type == 2){  //背景图
                            _this.dataForm.backgroundImage = response.object.saveImage;
                            _this.backgroundImageUrl = response.object.showImage;
                        }
                    }else{  //主图
                        _this.dataForm.coverImage = response.object.saveImage;
                        _this.imageUrl = response.object.showImage;
                    }
                }else{
                    this.$message.error(response.message);
                }
                
            })
        },
        //准备上传
        beforeAvatarUpload(file){
            const isJPG = file.type;
            const isLt2M = file.size / 1024 / 1024 < 4;
            if(((isJPG === 'image/jpeg') || (isJPG === 'image/png') || (isJPG === 'image/jpg') || (isJPG === 'image/gif') || (isJPG === 'image/JPEG') || (isJPG === 'image/PNG') || (isJPG === 'image/JPG') || (isJPG === 'image/GIF')) == false){
                this.$message.error('上传图片只能是 jpeg、png、jpg、gif 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 4MB!');
            }
            return isJPG && isLt2M;
        },
        //sku  规格  change
        productSkuChange(val){
            const _this = this;
            _this.productSkuValue = '';
            detailSpec(val).then(response => {
                if(response.code == 200){
                    _this.productSpecValueEntityList = response.object.productSpecValueEntityList;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //sku   规格   选择
        productSkuChoose(val){
            const _this = this;
            for(let i=0;i<_this.specList.length;i++){
                if(_this.specList[i].id == _this.productSkuId){
                    //判断是否已有该spu
                    let sub = -1;
                    for(let a=0;a<_this.tabSku.length;a++){
                        if(_this.tabSku[a].title == _this.specList[i].specName){
                            sub = a;
                        }
                    }
                    if(sub == -1){
                        _this.spuType++;
                        _this.tabSku.push({'title': _this.specList[i].specName, 'id': _this.specList[i].id});
                        for(let j=0;j<_this.specList[i].productSpecValueEntityList.length;j++){
                            if(_this.specList[i].productSpecValueEntityList[j].id == val){
                                let ind = _this.getArrIndex(_this.tabSku, {'title': _this.specList[i].specName, 'id': _this.specList[i].id});
                                _this.tabSkuShowArr.push([]);
                                _this.tabSkuShowArr[ind].push(_this.specList[i].productSpecValueEntityList[j].specValue);
                            }
                        }
                    }else{
                        _this.spuType = 1;
                        //判断是否有该spu相同，值不同
                        for(let j=0;j<_this.specList[i].productSpecValueEntityList.length;j++){
                            if(_this.specList[i].productSpecValueEntityList[j].id == val){
                                for(let k=0;k<_this.tabSkuShowArr.length;k++){
                                    let ind = _this.getArrIndex(_this.tabSku, {'title': _this.specList[i].specName, 'id': _this.specList[i].id});
                                    if(_this.tabSkuShowArr[ind].indexOf(_this.specList[i].productSpecValueEntityList[j].specValue) == -1){
                                        _this.tabSkuShowArr[ind].push(_this.specList[i].productSpecValueEntityList[j].specValue);
                                        _this.tabSkuSubmitArr.push({productCode: '', quantity: '', retailPrice: '', tradePrice: '', weight: ''});
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(_this.spuType == 2){
                _this.tabSkuSubmitArr.push({productCode: '', quantity: '', retailPrice: '', tradePrice: '', weight: ''});
            }
            _this.serialTableArray = _this.serialArray(_this.tabSkuShowArr);  //排列组合
            let tabSku = _this.tabSku;
            _this.tabAllSkuArr = [];  //sku基本数据
            for(let i=0;i<_this.serialTableArray.length;i++){
                _this.tabAllSkuArr.push({productCode: '', quantity: '', retailPrice: '', tradePrice: '', weight: ''});
                for(let j=0;j<tabSku.length;j++){
                    _this.tabAllSkuArr[i][tabSku[j].title] = _this.serialTableArray[i][j];
                }
            }
        },
        //数组对象查重
        getArrIndex(arr, obj){
            // arr数组，obj数组中的对象
            let index = null;
            let key = Object.keys(obj)[0];
            arr.every(function(value, i) {
                if (value[key] === obj[key]) {
                    index = i;
                    return false;
                }
                return true;
            });
            return index;
        },
        //sku  二维数组排列组合
        serialArray(arr){
            var lengthArr = [];  
            var productArr = []; 
            var result = [];
            var length = 1;
            for(var i = 0; i < arr.length; i++){
                var len = arr[i].length;
                lengthArr.push(len);
                var product = i === 0 ? 1 : arr[i - 1].length * productArr[i - 1];
                productArr.push(product);
                length *= len;
            }	
            for(var i = 0; i < length; i++){
                var resultItem = [];
                for(var j = 0; j < arr.length ; j ++){
                    resultItem.push(arr[j][Math.floor(i / productArr[j]) % lengthArr[j]])
                }
                result.push(resultItem);
            }
            return result
        },
        //spu   属性  模型   change
        productSpuChange(val){
            const _this = this;
            _this.productSpuList = [];
            detailProp(val).then(response => {
                if(response.code == 200){
                    if(response.object.productPropEntityVoList){
                        _this.productPropEntityVoList = response.object.productPropEntityVoList;
                        for(let j=0;j<_this.productPropEntityVoList.length;j++){  //  属性
                            _this.productPropEntityVo[j] = [];
                            for(let k=0;k<_this.productPropEntityVoList[j].productPropValueEntityList.length;k++){  //属性值
                                _this.productPropEntityVo[j][k] = '';
                            }
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //spu  扩展属性 change
        productPropEntityVoChange(valId, optlist, propId, propName, ind){
            this.productSpuList[ind] = {id: propId, name: propName, productPropEntityList:[]};
            for(let i=0;i<optlist.length;i++){
                for(let j=0;j<valId.length;j++){
                    if(valId[j] == optlist[i].id){
                        this.productSpuList[ind].productPropEntityList.push({id: valId[j], propName: optlist[i].propValue})
                    }
                }
            }
        },
        //是否组合产品  change
        combinedChange(val){
            if(val == 0){  //套餐
                this.showDialog = true;
            }else if(val == 1){  //单品
                this.showDialog = false;
            }
        },
        //添加产品
        addProductClick(formName){
            const _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //添加
                    _this.dataForm.productUnitEntityList.push({
                        unitProductId: _this.addProductForm.unitProductId,
                        quantity: _this.addProductForm.quantity,
                        sort: _this.addProductForm.sort
                    });
                    _this.productUnitArr = [];
                    for(let i=0;i<_this.dataForm.productUnitEntityList.length;i++){
                        for(let j=0;j<_this.productListOpt.length;j++){
                            if(_this.dataForm.productUnitEntityList[i].unitProductId == _this.productListOpt[j].id){
                                _this.productUnitArr.push(_this.productListOpt[j].name + '【' + _this.dataForm.productUnitEntityList[i].quantity +'】');
                            }
                        }
                    }
                    _this.cancelProductClick('addProductForm',1);
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //移除产品
        handleClose(item,index){
            this.productUnitArr.splice(index,1);
            this.dataForm.productUnitEntityList.splice(index,1);
            this.cancelProductClick('addProductForm',1);
        },
        //取消添加套餐
        cancelProductClick(formName,type){
            this.$refs[formName].resetFields();
            if(!type){
                this.showDialog = false;
            }
        },
        //套餐  添加产品
        openAddProduct(){
            this.showDialog = true;
        },
        ////删除  sku  基本数据
        delTabColOne(ind){
            this.tabAllSkuArr.splice(ind,1);
        },
        //spu编辑器上传
        qnSpuUpload(param){
            this.qnUpload(param,'spu')
        },
        // 编辑器上传
        qnUpload(param,type) {
            const _this = this;
            let formData = new FormData();
            formData.append('photoFile', param.file);
            if(type){
                formData.append('dir', 'ProductProperty');
            }else{
                formData.append('dir', 'Product');
            }
            if (this.uploadType === 'image') {  // 如果是点击插入图片
                formData.append('fileType', '1');
                return uploadPic(formData).then(re => {
                    if(re.code == 200){
                        if(type){
                            _this.addRange = _this.$refs.mySpuQuillEditor.quill.getSelection();
                            _this.uploadSpuData.push({
                                saveImage: re.object.saveImage,
                                showImage: re.object.showImage,
                                type: _this.uploadType,
                            })
                            _this.$refs.mySpuQuillEditor.quill.insertEmbed(_this.addRange !== null ? _this.addRange.index : 0, _this.uploadType, re.object.saveImage, Quill.sources.USER)   // 调用编辑器的 insertEmbed 方法，插入URL
                            let spustr = _this.spuDescription;
                            let sub = spustr.indexOf('<img src="'+ re.object.saveImage +'">');
                            spustr = spustr.replace('<img src="'+ re.object.saveImage +'">','');
                            spustr = spustr.slice(0,sub) + '<img  src="'+ re.object.showImage +'">' + spustr.slice(sub,spustr.length - 1);
                            _this.spuDescription = spustr;
                            _this.$refs.mySpuQuillEditor.quill.setSelection(_this.$refs.mySpuQuillEditor.quill.getSelection().index+1);
                        }else{
                            _this.addRange = _this.$refs.myQuillEditor.quill.getSelection();
                            _this.uploadData.push({
                                saveImage: re.object.saveImage,
                                showImage: re.object.showImage,
                                type: _this.uploadType,
                            })
                            _this.$refs.myQuillEditor.quill.insertEmbed(_this.addRange !== null ? _this.addRange.index : 0, _this.uploadType, re.object.saveImage, Quill.sources.USER)   // 调用编辑器的 insertEmbed 方法，插入URL
                            let str = _this.description;
                            let sub = str.indexOf('<img src="'+ re.object.saveImage +'">');
                            str = str.replace('<img src="'+ re.object.saveImage +'">','');
                            str = str.slice(0,sub) + '<img  src="'+ re.object.showImage +'">' + str.slice(sub,str.length - 1);
                            _this.description = str;
                            _this.$refs.myQuillEditor.quill.setSelection(_this.$refs.myQuillEditor.quill.getSelection().index+1);
                        }
                        
                        
                    }else{
                        this.$message.error(re.message);
                    }
                })
            } else if (this.uploadType === 'video') {  // 如果是点击插入视频
                formData.append('fileType', '2');
                return uploadPic(formData).then(re => {
                    if(re.code == 200){
                        if(type){
                            _this.addRange = _this.$refs.mySpuQuillEditor.quill.getSelection();
                            _this.uploadSpuData.push({
                                saveImage: re.object.saveImage,
                                showImage: re.object.showImage,
                                type: _this.uploadType,
                            })
                            _this.$refs.mySpuQuillEditor.quill.insertEmbed(_this.addRange !== null ? _this.addRange.index : 0, _this.uploadType, re.object.saveImage, Quill.sources.USER)   // 调用编辑器的 insertEmbed 方法，插入URL
                            let spustr = _this.spuDescription;
                            let sub = spustr.indexOf('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ re.object.saveImage +'"></iframe>');
                            spustr = spustr.replace('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ re.object.saveImage +'"></iframe>','');
                            spustr = spustr.slice(0,sub) + '<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ re.object.showImage +'"></iframe>' + spustr.slice(sub,spustr.length - 1);
                            _this.spuDescription = spustr;
                            _this.$refs.mySpuQuillEditor.quill.setSelection(_this.$refs.mySpuQuillEditor.quill.getSelection().index+1);
                        }else{
                            _this.addRange = _this.$refs.myQuillEditor.quill.getSelection();
                            _this.uploadData.push({
                                saveImage: re.object.saveImage,
                                showImage: re.object.showImage,
                                type: _this.uploadType,
                            })
                            _this.$refs.myQuillEditor.quill.insertEmbed(_this.addRange !== null ? _this.addRange.index : 0, _this.uploadType, re.object.saveImage, Quill.sources.USER)   // 调用编辑器的 insertEmbed 方法，插入URL
                            let str = _this.description;
                            let sub = str.indexOf('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ re.object.saveImage +'"></iframe>');
                            str = str.replace('<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ re.object.saveImage +'"></iframe>','');
                            str = str.slice(0,sub) + '<iframe class="ql-video" frameborder="0" allowfullscreen="true" src="'+ re.object.showImage +'"></iframe>' + str.slice(sub,str.length - 1);
                            _this.description = str;
                            _this.$refs.myQuillEditor.quill.setSelection(_this.$refs.myQuillEditor.quill.getSelection().index+1);
                        }
                        
                    }else{
                        this.$message.error(re.message);
                    }
                })
            }
        },
        // 点击图片ICON触发事件
        imgHandler(state){
            this.Handler(state,'image');
        },
        // 点击视频ICON触发事件
        videoHandler(state){
            this.Handler(state,'video');
        },
        imgSpuHandler(state){
            this.Handler(state,'image','spu');
        },
        videoSpuHandler(state){
            this.Handler(state,'video','spu');
        },
        Handler(state,type,item) {
            if(item){
                this.addRange = this.$refs.mySpuQuillEditor.quill.getSelection()
            }else{
                this.addRange = this.$refs.myQuillEditor.quill.getSelection()
            }
            if (state) {
                let fileInput;
                if(item){
                    fileInput = document.getElementById('imgSpuInput')
                }else{
                    fileInput = document.getElementById('imgInput')
                }
                fileInput.click() // 加一个触发事件
            }
            this.uploadType = type
        },
    },
    mounted(){
        this.init();
        this.getCategoryList();
        this.getProductSku();
        this.getProductSpu();
        this.preferentialList();
        // 为图片ICON绑定事件  getModule 为编辑器的内部属性   产品描述
        this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)
        this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('video', this.videoHandler)  // 为视频ICON绑定事件
        //spu描述
        this.$refs.mySpuQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgSpuHandler)
        this.$refs.mySpuQuillEditor.quill.getModule('toolbar').addHandler('video', this.videoSpuHandler)  // 为视频ICON绑定事件
    }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style>
    .quill-editor {height: 500px;}
    .quill-editor .ql-container {height: 480px;}

    .limit {
        height: 30px;
        border: 1px solid #ccc;
        line-height: 30px;
        text-align: right;
    }
    .limit span{color: #ee2a7b;}

    .ql-snow .ql-editor img {
        max-width: 480px;
    }

    .ql-editor .ql-video {
        max-width: 480px;
    }
</style>
